home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_python.idb / usr / freeware / lib / python1.5 / smtplib.py.z / smtplib.py
Encoding:
Python Source  |  1999-04-16  |  14.9 KB  |  450 lines

  1. #! /usr/bin/env python
  2.  
  3. '''SMTP/ESMTP client class.
  4.  
  5. Author: The Dragon De Monsyne <dragondm@integral.org>
  6. ESMTP support, test code and doc fixes added by
  7.     Eric S. Raymond <esr@thyrsus.com>
  8. Better RFC 821 compliance (MAIL and RCPT, and CRLF in data)
  9.     by Carey Evans <c.evans@clear.net.nz>, for picky mail servers.
  10.    
  11. This was modified from the Python 1.5 library HTTP lib.
  12.  
  13. This should follow RFC 821 (SMTP) and RFC 1869 (ESMTP).
  14.  
  15. Notes:
  16.  
  17. Please remember, when doing ESMTP, that the names of the SMTP service
  18. extensions are NOT the same thing as the option keywords for the RCPT
  19. and MAIL commands!
  20.  
  21. Example:
  22.  
  23.   >>> import smtplib
  24.   >>> s=smtplib.SMTP("localhost")
  25.   >>> print s.help()
  26.   This is Sendmail version 8.8.4
  27.   Topics:
  28.       HELO    EHLO    MAIL    RCPT    DATA
  29.       RSET    NOOP    QUIT    HELP    VRFY
  30.       EXPN    VERB    ETRN    DSN
  31.   For more info use "HELP <topic>".
  32.   To report bugs in the implementation send email to
  33.       sendmail-bugs@sendmail.org.
  34.   For local information send email to Postmaster at your site.
  35.   End of HELP info
  36.   >>> s.putcmd("vrfy","someone@here")
  37.   >>> s.getreply()
  38.   (250, "Somebody OverHere <somebody@here.my.org>")
  39.   >>> s.quit()
  40. '''
  41.  
  42. import socket
  43. import string
  44. import re
  45. import rfc822
  46. import types
  47.  
  48. SMTP_PORT = 25
  49. CRLF="\r\n"
  50.  
  51. # used for exceptions 
  52. class SMTPException(Exception): pass
  53. class SMTPServerDisconnected(SMTPException): pass
  54. class SMTPSenderRefused(SMTPException): pass
  55. class SMTPRecipientsRefused(SMTPException): pass
  56. class SMTPDataError(SMTPException): pass
  57.  
  58. def quoteaddr(addr):
  59.     """Quote a subset of the email addresses defined by RFC 821.
  60.  
  61.     Should be able to handle anything rfc822.parseaddr can handle.
  62.     """
  63.     m=None
  64.     try:
  65.         m=rfc822.parseaddr(addr)[1]
  66.     except AttributeError:
  67.         pass
  68.     if not m:
  69.         #something weird here.. punt -ddm
  70.         return addr
  71.     else:
  72.         return "<%s>" % m
  73.  
  74. def quotedata(data):
  75.     """Quote data for email.
  76.  
  77.     Double leading '.', and change Unix newline '\n', or Mac '\r' into
  78.     Internet CRLF end-of-line.
  79.     """
  80.     return re.sub(r'(?m)^\.', '..',
  81.         re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))
  82.  
  83. class SMTP:
  84.     """This class manages a connection to an SMTP or ESMTP server.
  85.     SMTP Objects:
  86.         SMTP objects have the following attributes:    
  87.             helo_resp 
  88.                 This is the message given by the server in responce to the 
  89.                 most recent HELO command.
  90.                 
  91.             ehlo_resp
  92.                 This is the message given by the server in responce to the 
  93.                 most recent EHLO command. This is usually multiline.
  94.  
  95.             does_esmtp 
  96.                 This is a True value _after you do an EHLO command_, if the
  97.                 server supports ESMTP.
  98.  
  99.             esmtp_features 
  100.                 This is a dictionary, which, if the server supports ESMTP,
  101.                 will  _after you do an EHLO command_, contain the names of the
  102.                 SMTP service  extentions this server supports, and their 
  103.                 parameters (if any).
  104.                 Note, all extention names are mapped to lower case in the 
  105.                 dictionary. 
  106.  
  107.         For method docs, see each method's docstrings. In general, there is 
  108.             a method of the same name to perform each SMTP command, and there 
  109.             is a method called 'sendmail' that will do an entire mail 
  110.             transaction.
  111.     """
  112.     debuglevel = 0
  113.     file = None
  114.     helo_resp = None
  115.     ehlo_resp = None
  116.     does_esmtp = 0
  117.  
  118.     def __init__(self, host = '', port = 0):
  119.         """Initialize a new instance.
  120.  
  121.         If specified, `host' is the name of the remote host to which to
  122.         connect.  If specified, `port' specifies the port to which to connect.
  123.         By default, smtplib.SMTP_PORT is used.
  124.  
  125.         """
  126.         self.esmtp_features = {}
  127.         if host: self.connect(host, port)
  128.     
  129.     def set_debuglevel(self, debuglevel):
  130.         """Set the debug output level.
  131.  
  132.         A non-false value results in debug messages for connection and for all
  133.         messages sent to and received from the server.
  134.  
  135.         """
  136.         self.debuglevel = debuglevel
  137.  
  138.     def connect(self, host='localhost', port = 0):
  139.         """Connect to a host on a given port.
  140.  
  141.         If the hostname ends with a colon (`:') followed by a number, and
  142.         there is no port specified, that suffix will be stripped off and the
  143.         number interpreted as the port number to use.
  144.  
  145.         Note: This method is automatically invoked by __init__, if a host is
  146.         specified during instantiation.
  147.  
  148.         """
  149.         if not port:
  150.             i = string.find(host, ':')
  151.             if i >= 0:
  152.                 host, port = host[:i], host[i+1:]
  153.                 try: port = string.atoi(port)
  154.                 except string.atoi_error:
  155.                     raise socket.error, "nonnumeric port"
  156.         if not port: port = SMTP_PORT
  157.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  158.         if self.debuglevel > 0: print 'connect:', (host, port)
  159.         self.sock.connect(host, port)
  160.         (code,msg)=self.getreply()
  161.         if self.debuglevel >0 : print "connect:", msg
  162.         return msg
  163.     
  164.     def send(self, str):
  165.         """Send `str' to the server."""
  166.         if self.debuglevel > 0: print 'send:', `str`
  167.         if self.sock:
  168.             try:
  169.                 self.sock.send(str)
  170.             except socket.error:
  171.                 raise SMTPServerDisconnected('Server not connected')
  172.         else:
  173.             raise SMTPServerDisconnected('please run connect() first')
  174.  
  175.     def putcmd(self, cmd, args=""):
  176.         """Send a command to the server."""
  177.         str = '%s %s%s' % (cmd, args, CRLF)
  178.         self.send(str)
  179.     
  180.     def getreply(self):
  181.         """Get a reply from the server.
  182.         
  183.         Returns a tuple consisting of:
  184.  
  185.           - server response code (e.g. '250', or such, if all goes well)
  186.             Note: returns -1 if it can't read response code.
  187.  
  188.           - server response string corresponding to response code (multiline
  189.             responses are converted to a single, multiline string).
  190.         """
  191.         resp=[]
  192.         self.file = self.sock.makefile('rb')
  193.         while 1:
  194.             line = self.file.readline()
  195.             if self.debuglevel > 0: print 'reply:', `line`
  196.             resp.append(string.strip(line[4:]))
  197.             code=line[:3]
  198.             #check if multiline resp
  199.             if line[3:4]!="-":
  200.                 break
  201.         try:
  202.             errcode = string.atoi(code)
  203.         except(ValueError):
  204.             errcode = -1
  205.  
  206.         errmsg = string.join(resp,"\n")
  207.         if self.debuglevel > 0: 
  208.             print 'reply: retcode (%s); Msg: %s' % (errcode,errmsg)
  209.         return errcode, errmsg
  210.     
  211.     def docmd(self, cmd, args=""):
  212.         """Send a command, and return its response code."""
  213.         self.putcmd(cmd,args)
  214.         (code,msg)=self.getreply()
  215.         return code
  216.  
  217.     # std smtp commands
  218.     def helo(self, name=''):
  219.         """SMTP 'helo' command.
  220.         Hostname to send for this command defaults to the FQDN of the local
  221.         host.
  222.         """
  223.         name=string.strip(name)
  224.         if len(name)==0:
  225.             name=socket.gethostbyaddr(socket.gethostname())[0]
  226.         self.putcmd("helo",name)
  227.         (code,msg)=self.getreply()
  228.         self.helo_resp=msg
  229.         return code
  230.  
  231.     def ehlo(self, name=''):
  232.         """ SMTP 'ehlo' command.
  233.         Hostname to send for this command defaults to the FQDN of the local
  234.         host.
  235.         """
  236.         name=string.strip(name)
  237.         if len(name)==0:
  238.             name=socket.gethostbyaddr(socket.gethostname())[0]
  239.         self.putcmd("ehlo",name)
  240.         (code,msg)=self.getreply()
  241.         # According to RFC1869 some (badly written) 
  242.         # MTA's will disconnect on an ehlo. Toss an exception if 
  243.         # that happens -ddm
  244.         if code == -1 and len(msg) == 0:
  245.             raise SMTPServerDisconnected("Server not connected")
  246.         self.ehlo_resp=msg
  247.         if code<>250:
  248.             return code
  249.         self.does_esmtp=1
  250.         #parse the ehlo responce -ddm
  251.         resp=string.split(self.ehlo_resp,'\n')
  252.         del resp[0]
  253.         for each in resp:
  254.             m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*)',each)
  255.             if m:
  256.                 feature=string.lower(m.group("feature"))
  257.                 params=string.strip(m.string[m.end("feature"):])
  258.                 self.esmtp_features[feature]=params
  259.         return code
  260.  
  261.     def has_extn(self, opt):
  262.         """Does the server support a given SMTP service extension?"""
  263.         return self.esmtp_features.has_key(string.lower(opt))
  264.  
  265.     def help(self, args=''):
  266.         """SMTP 'help' command.
  267.         Returns help text from server."""
  268.         self.putcmd("help", args)
  269.         (code,msg)=self.getreply()
  270.         return msg
  271.  
  272.     def rset(self):
  273.         """SMTP 'rset' command -- resets session."""
  274.         code=self.docmd("rset")
  275.         return code
  276.  
  277.     def noop(self):
  278.         """SMTP 'noop' command -- doesn't do anything :>"""
  279.         code=self.docmd("noop")
  280.         return code
  281.  
  282.     def mail(self,sender,options=[]):
  283.         """SMTP 'mail' command -- begins mail xfer session."""
  284.         optionlist = ''
  285.         if options and self.does_esmtp:
  286.             optionlist = string.join(options, ' ')
  287.         self.putcmd("mail", "FROM:%s %s" % (quoteaddr(sender) ,optionlist))
  288.         return self.getreply()
  289.  
  290.     def rcpt(self,recip,options=[]):
  291.         """SMTP 'rcpt' command -- indicates 1 recipient for this mail."""
  292.         optionlist = ''
  293.         if options and self.does_esmtp:
  294.             optionlist = ' ' + string.join(options, ' ')
  295.         self.putcmd("rcpt","TO:%s%s" % (quoteaddr(recip),optionlist))
  296.         return self.getreply()
  297.  
  298.     def data(self,msg):
  299.         """SMTP 'DATA' command -- sends message data to server. 
  300.         Automatically quotes lines beginning with a period per rfc821.
  301.         """
  302.         self.putcmd("data")
  303.         (code,repl)=self.getreply()
  304.         if self.debuglevel >0 : print "data:", (code,repl)
  305.         if code <> 354:
  306.             return -1
  307.         else:
  308.             self.send(quotedata(msg))
  309.             self.send("%s.%s" % (CRLF, CRLF))
  310.             (code,msg)=self.getreply()
  311.             if self.debuglevel >0 : print "data:", (code,msg)
  312.             return code
  313.  
  314.     def verify(self, address):
  315.         """SMTP 'verify' command -- checks for address validity."""
  316.         self.putcmd("vrfy", quoteaddr(address))
  317.         return self.getreply()
  318.     # a.k.a.
  319.     vrfy=verify
  320.  
  321.     def expn(self, address):
  322.         """SMTP 'verify' command -- checks for address validity."""
  323.         self.putcmd("expn", quoteaddr(address))
  324.         return self.getreply()
  325.  
  326.     # some useful methods
  327.     def sendmail(self, from_addr, to_addrs, msg, mail_options=[],
  328.                  rcpt_options=[]): 
  329.         """This command performs an entire mail transaction. 
  330.  
  331.         The arguments are: 
  332.             - from_addr    : The address sending this mail.
  333.             - to_addrs     : A list of addresses to send this mail to.  A bare
  334.                              string will be treated as a list with 1 address.
  335.             - msg          : The message to send. 
  336.             - mail_options : List of ESMTP options (such as 8bitmime) for the
  337.                              mail command.
  338.             - rcpt_options : List of ESMTP options (such as DSN commands) for
  339.                              all the rcpt commands.
  340.  
  341.         If there has been no previous EHLO or HELO command this session, this
  342.         method tries ESMTP EHLO first.  If the server does ESMTP, message size
  343.         and each of the specified options will be passed to it.  If EHLO
  344.         fails, HELO will be tried and ESMTP options suppressed.
  345.  
  346.         This method will return normally if the mail is accepted for at least
  347.         one recipient.  Otherwise it will throw an exception (either
  348.         SMTPSenderRefused, SMTPRecipientsRefused, or SMTPDataError) That is,
  349.         if this method does not throw an exception, then someone should get
  350.         your mail.  If this method does not throw an exception, it returns a
  351.         dictionary, with one entry for each recipient that was refused.
  352.  
  353.         Example:
  354.       
  355.          >>> import smtplib
  356.          >>> s=smtplib.SMTP("localhost")
  357.          >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
  358.          >>> msg = '''
  359.          ... From: Me@my.org
  360.          ... Subject: testin'...
  361.          ...
  362.          ... This is a test '''
  363.          >>> s.sendmail("me@my.org",tolist,msg)
  364.          { "three@three.org" : ( 550 ,"User unknown" ) }
  365.          >>> s.quit()
  366.         
  367.         In the above example, the message was accepted for delivery to three
  368.         of the four addresses, and one was rejected, with the error code
  369.         550. If all addresses are accepted, then the method will return an
  370.         empty dictionary.
  371.  
  372.         """
  373.         if not self.helo_resp and not self.ehlo_resp:
  374.             if self.ehlo() >= 400:
  375.                 self.helo()
  376.         esmtp_opts = []
  377.         if self.does_esmtp:
  378.             # Hmmm? what's this? -ddm
  379.             # self.esmtp_features['7bit']=""
  380.             if self.has_extn('size'):
  381.                 esmtp_opts.append("size=" + `len(msg)`)
  382.             for option in mail_options:
  383.                 esmtp_opts.append(option)
  384.  
  385.         (code,resp) = self.mail(from_addr, esmtp_opts)
  386.         if code <> 250:
  387.             self.rset()
  388.             raise SMTPSenderRefused('%s: %s' % (from_addr, resp))
  389.         senderrs={}
  390.         if type(to_addrs) == types.StringType:
  391.             to_addrs = [to_addrs]
  392.         for each in to_addrs:
  393.             (code,resp)=self.rcpt(each, rcpt_options)
  394.             if (code <> 250) and (code <> 251):
  395.                 senderrs[each]=(code,resp)
  396.         if len(senderrs)==len(to_addrs):
  397.             # the server refused all our recipients
  398.             self.rset()
  399.             raise SMTPRecipientsRefused(string.join(
  400.         map(lambda x:"%s: %s" % (x[0], x[1][1]), senderrs.items()),
  401.                     '; '))
  402.         code=self.data(msg)
  403.         if code <>250 :
  404.             self.rset()
  405.             raise SMTPDataError('data transmission error: %s' % code)
  406.         #if we got here then somebody got our mail
  407.         return senderrs         
  408.  
  409.  
  410.     def close(self):
  411.         """Close the connection to the SMTP server."""
  412.         if self.file:
  413.             self.file.close()
  414.         self.file = None
  415.         if self.sock:
  416.             self.sock.close()
  417.         self.sock = None
  418.  
  419.  
  420.     def quit(self):
  421.         """Terminate the SMTP session."""
  422.         self.docmd("quit")
  423.         self.close()
  424.  
  425.  
  426. # Test the sendmail method, which tests most of the others.
  427. # Note: This always sends to localhost.
  428. if __name__ == '__main__':
  429.     import sys, rfc822
  430.  
  431.     def prompt(prompt):
  432.         sys.stdout.write(prompt + ": ")
  433.         return string.strip(sys.stdin.readline())
  434.  
  435.     fromaddr = prompt("From")
  436.     toaddrs  = string.splitfields(prompt("To"), ',')
  437.     print "Enter message, end with ^D:"
  438.     msg = ''
  439.     while 1:
  440.         line = sys.stdin.readline()
  441.         if not line:
  442.             break
  443.         msg = msg + line
  444.     print "Message length is " + `len(msg)`
  445.  
  446.     server = SMTP('localhost')
  447.     server.set_debuglevel(1)
  448.     server.sendmail(fromaddr, toaddrs, msg)
  449.     server.quit()
  450.